package com.nflakes.petrol.services

import com.nflakes.petrol.model.PetrolStation
import com.nflakes.petrol.model.PetrolStations

class GroovySlurperService implements SlurperService {

  public PetrolStations slurpPetrolStations() {
    PetrolStations petrolStations = new PetrolStations()

    def slurper = new XmlSlurper(new org.ccil.cowan.tagsoup.Parser())
    ['95', '98', 'o', 'e'].each { petrolType ->
      (0..2).each { counter ->
        def url = new URL("http://cenapaliw.pl/?p=" + counter + "&m=" + petrolType);
        url.withReader { reader ->
          def html = slurper.parse(reader);

          html.body.div.breadthFirst().each() { element ->

            if (element.@id.equals("priser")) {

              element.tr.list().each { it ->
                String[] tableRow = it.td.list();
                if (tableRow.length == 4) {
                  petrolStations.add(PetrolStation.fromTable(tableRow));
                }
              }
            }
          }
        }
      }
    }
    return petrolStations
  }
}
